#include <iostream>
#include <stdlib.h>
#include <unistd.h>
#include <string>


bool GetQueryString(std::string& query_string){
  std::string method = getenv("METHOD_ENV");
  if (method == "GET"){
    std::cerr << "Debug Query_string: " << getenv("QUERY_STRING") <<std::endl;
    query_string = getenv("QUERY_STRING");
    return true;
  }
  else if(method == "POST"){
    int content_length = atoi(getenv("CONTENT_LENGTH"));
    char ch = 0;
    while (content_length--){
      read(0, &ch, 1);
      query_string.push_back(ch);
    }
    return true;
  }
  return false;
}

bool CutString(std::string& target, std::string& key_out, std::string& value_out, std::string sep){
  size_t pos = target.find(sep);
  if (pos != std::string::npos){
    key_out = target.substr(0, pos);
    value_out = target.substr(pos + sep.size());
    return true;
  }
  return false;
}



int main(){
  std::string query_string;
  GetQueryString(query_string);
   
  std::string str1;
  std::string str2;
  CutString(query_string, str1, str2, "&");

  std::string name1;
  std::string value1;
  CutString(str1, name1, value1, "=");

  std::string name2;
  std::string value2;
  CutString(str2, name2, value2, "=");

  std::cout << "name1 : vale1" << name1 << ":" << value1 << std::endl;
  std::cout << "name2 : vale2" << name2 << ":" << value2 << std::endl;
  return 0;
}
